package com.fc.happyteam.common.convert;


import com.fc.happyteam.dto.sku.SkuDto;
import com.fc.happyteam.dto.sku.SkuPriceDto;
import com.fc.happyteam.entity.SkuEntity;
import com.fc.happyteam.entity.SkuPriceDuration;
import com.fc.happyteam.entity.SkuPriceEntity;

import java.math.BigDecimal;
import java.util.*;

import static com.fc.happyteam.utils.DateUtils.between;

public class SkuConverter implements ObjectConverter{
    @Override
    public void convertFromDto(Object source, Object target) {
        SkuDto skuDto = (SkuDto) source;
        if(skuDto.getPriceList() != null){
            for(SkuPriceDto skuPriceDto : skuDto.getPriceList()){
                SkuPriceDuration.fromString(skuPriceDto.getDuration());
            }
        }
    }

    @Override
    public void convertToDto(Object source, Object target) {
        SkuEntity skuEntity = (SkuEntity) source;
        if(skuEntity.getPriceList() != null && skuEntity.getPriceList().size() > 0){

            List<SkuPriceEntity> list = new ArrayList<>();
            for(SkuPriceEntity skuPriceEntity : skuEntity.getPriceList()){
                if(between(skuPriceEntity.getFrom(), skuPriceEntity.getTo())){
                    list.add(skuPriceEntity);
                }
            }

            if(list.size() == 0){
                list.addAll(skuEntity.getPriceList());
            }

            Collections.sort(list, new Comparator<SkuPriceEntity>() {
                @Override
                public int compare(SkuPriceEntity o1, SkuPriceEntity o2) {
                    return (int)(o1.getPriceId() - o2.getPriceId());
                }
            });

            SkuPriceEntity basePrice = list.get(0);
            ((SkuDto) target).setPricePerHour(
                    basePrice.getPrice().divide(
                            new BigDecimal(SkuPriceDuration.fromString(
                                    basePrice.getDuration()).getHours()),
                    1, BigDecimal.ROUND_HALF_UP));
        }
    }
}
